package cn.com.xy.sms.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONObject;

import android.app.Activity;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.MatchCacheManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.DuoquUtils;
import cn.com.xy.sms.sdk.util.StringUtils;
/*SDK-720 songzhirong 20170117 start */
public class ParseFavoriteManager {

	public static void addToFavorite(String msgId, String phone,
			String content, long smsReceiveTime,final HashMap<String, Object> extend) {
		MatchCacheManager.updateMarkAndFavoriteAsy(msgId, phone, content, 1, 1);
	}

	public static void cancelFavorite(String msgId, String phone,
			String content, long smsReceiveTime,final HashMap<String, Object> extend) {
		MatchCacheManager.updateMarkAndFavoriteAsy(msgId, phone, content, 0, 0);

	}

	private static HashSet<String> cachePhoneSet = new HashSet<String>();

	public static void loadFavoriteBubbleData(Activity context) {
		try {
			String where = "is_favorite=?";
			String args[] = new String[] { "1" };
			Map<String, JSONObject> richBubbleData = MatchCacheManager
					.loadDataByParam(where, args);

			if (richBubbleData == null || richBubbleData.isEmpty()) {
				return;
			}

			Map<String, HashMap<String, JSONObject>> phoneCacheMap = new HashMap<String, HashMap<String, JSONObject>>();

			cachePhoneSet.clear();

			for (Map.Entry<String, JSONObject> entry : richBubbleData
					.entrySet()) {

				JSONObject item = entry.getValue();
				if (item == null
						|| StringUtils.isNull(item.optString("phonenum"))) {
					continue;
				}
				String phone = item.optString("phonenum");

				cachePhoneSet.add(phone);				

				HashMap<String, JSONObject> tempMap = phoneCacheMap.get(phone);
				if (tempMap == null) {
					tempMap = new HashMap<String, JSONObject>();
					tempMap.put(entry.getKey(), item);
					phoneCacheMap.put(phone, tempMap);
				} else {
					tempMap.put(entry.getKey(), item);
				}
			}
			
			

			for (Entry<String, HashMap<String, JSONObject>> entry : phoneCacheMap
					.entrySet()) {
				String key = entry.getKey();
				if (StringUtils.isNull(key)) {
					continue;
				}
				ParseRichBubbleManager.pubBubbleData(key, entry.getValue(),
						true);

			}
			
			DuoquUtils.getSdkDoAction().beforeInitBubbleView(context, cachePhoneSet);
			
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, "loadFavoriteBubbleData: ", e);

		}

	}

	public static void clearCache() {
		if (cachePhoneSet == null || cachePhoneSet.isEmpty()) {
			return;
		}
		try {
			Iterator<String> it = cachePhoneSet.iterator();
			while (it.hasNext()) {
				String phoneNum = it.next();
				ParseRichBubbleManager.clearCacheBubbleData(phoneNum);

			}
		} catch (Throwable e) {
			LogManager.e(Constant.TAG, "clearCache: ", e);

		}

	}
}
/*SDK-720 songzhirong 20170117 end */

